<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="短剧名称" prop="dramaTitle">
              <el-input v-model="queryParams.dramaTitle" placeholder="请输入短剧名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="广告主id" prop="thirdAdvertiserId">
              <el-input v-model="queryParams.thirdAdvertiserId" placeholder="请输入广告主id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="推广链接id" prop="referralLinkId">
              <el-input v-model="queryParams.referralLinkId" placeholder="请输入推广链接id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="投放人" prop="createName">
              <el-input v-model="queryParams.createName" placeholder="请输入投放人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="推广链接类型" prop="referralLinkType">
              <el-select v-model="queryParams.referralLinkType" clearable placeholder="请输入推广链接类型">
                <el-option v-for="(item, key) in appTypeList" :key="key" :value="item.type" :label="item.desc"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="启用状态" prop="pullStatus">
              <el-select v-model="queryParams.pullStatus" clearable placeholder="请选择启用状态">
                <el-option :value="1" label="启用"> </el-option>
                <el-option :value="0" label="停用"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <!--              <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oce:advertiserReferralRelation:export']"-->
              <!--                >导出</el-button-->
              <!--              >-->
              <el-button type="success" icon="Edit" @click="handleAdd" v-hasPermi="['oce:advertiserReferralRelation:add']">新增</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <listView :list="sum" />
      <el-table
        v-loading="loading"
        :data="advertiserReferralRelationList"
        @sort-change="sortChangeHandel"
        @selection-change="handleSelectionChange"
        :height="computeHeight()"
      >
        <el-table-column label="第三方广告主账户" minWidth="220">
          <template #default="{ row }">
            <div class="content-wrap">
              <div>
                账户ID:
                <el-text type="danger">
                  <span class="cursor-pointer underline" v-copyText="row.thirdAdvertiserId">{{ row.thirdAdvertiserId }}</span>
                </el-text>
              </div>
              <div>
                账户名:
                <span>{{ row.thirdAdvertiserName || '-' }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="推广链接" prop="referralLinkId" minWidth="220">
          <template #default="{ row }">
            <div class="content-wrap">
              <div>
                推广链接ID:
                <el-text type="danger">
                  <span class="cursor-pointer underline" v-copyText="row.referralLinkId">{{ row.referralLinkId }}</span>
                </el-text>
              </div>
              <div>
                推广名称:
                <span>{{ row.referralLinkName || '-' }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="短剧名称" prop="dramaTitle" minWidth="200">
          <template #default="{ row }">
            <el-text type="danger">
              <span class="cursor-pointer underline" v-copyText="row.dramaTitle">{{ row.dramaTitle }}</span>
            </el-text>
          </template>
        </el-table-column>
        <el-table-column label="投放人" prop="createName" minWidth="80"></el-table-column>
        <el-table-column label="拉取数据开始时间" prop="createTime" minWidth="160" sortable="custom"></el-table-column>
        <el-table-column label="拉取数据结束时间" prop="endTime" minWidth="160" sortable="custom"></el-table-column>
        <el-table-column label="应用类型" prop="appType" minWidth="90">
          <template #default="{ row }">
            <el-tag v-if="row.appType === 1" key="el-tag-1" type="warning" size="small">抖小</el-tag>
            <el-tag v-else-if="row.appType === 3" key="el-tag-2" size="small">微小</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="推广链接类型" prop="referralLinkType" minWidth="110">
          <template #default="{ row }">
            {{ appTypeList.find((v) => v.type * 1 === row.referralLinkType)?.desc || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="拉取启用状态" prop="pullStatus" minWidth="110">
          <template #default="{ row }">
            <div v-hasPermi="['oce:advertiserReferralRelation:stop']">
              <el-switch
                v-model="row.pullStatus"
                style="--el-switch-on-color: var(--el-color-success); --el-switch-off-color: var(--el-color-danger)"
                inlinePrompt
                activeText="启用"
                inactiveText="停用"
                :activeValue="1"
                :inactiveValue="0"
                :loading="row._statusLoading"
                @change="handleSetStateSingle(row)"
              ></el-switch>
            </div>
            <div v-if="computePermission">
              <el-tag :type="row.pullStatus == 1 ? 'success' : 'danger'" size="small" key="el-tag-1">
                {{ row.pullStatus == 1 ? '启用' : '停用' }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="pullStatus" minWidth="110">
          <template #default="scope">
            <div>
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oce:advertiserReferralRelation:edit']"
                >修改</el-button
              >
            </div>
            <div>
              <el-button link type="primary" icon="Compass" @click="clickHandle(scope.row)" v-hasPermi="['oce:advertiserReferralRelation:edit']"
                >每日消耗</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改推广链接-广告主关联对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="advertiserReferralRelationFormRef" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="广告主账号" prop="thirdAdvertiserName">
          <el-select
            v-model="form.thirdAdvertiserName"
            filterable
            remote
            reserve-keyword
            placeholder="请输入广告主账号"
            :loading="formLoading"
            :remote-method="remotePerformer"
          >
            <el-option v-for="(item, key) in relationList" :key="key" :label="item.thirdAdvertiserName" :value="item.thirdAdvertiserName" />
          </el-select>
        </el-form-item>
        <el-form-item label="推广链接id" prop="referralLinkId">
          <el-input v-model="form.referralLinkId" placeholder="请输入推广链接id" />
        </el-form-item>
        <el-form-item label="短剧名称" prop="dramaTitle">
          <el-input v-model="form.dramaTitle" placeholder="请输入短剧名称" />
        </el-form-item>
        <el-form-item label="投手名称" prop="createName">
          <el-input v-model="form.createName" placeholder="请输入投手名称" />
        </el-form-item>
        <el-form-item label="推广链接类型" prop="referralLinkType">
          <el-select v-model="form.referralLinkType" clearable placeholder="请输入推广链接类型">
            <el-option v-for="(item, key) in appTypeList" :key="key" :value="item.type * 1" :label="item.desc"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用类型" prop="appType">
          <el-select v-model="form.appType" clearable placeholder="请输入应用类型">
            <el-option v-for="(item, key) in linkTypeList" :key="key" :value="item.type * 1" :label="item.desc"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!form.advertiserReferralId" label="启用状态" prop="pullStatus">
          <el-switch
            style="--el-switch-on-color: var(--el-color-success); --el-switch-off-color: var(--el-color-danger)"
            v-model="form.pullStatus"
            inline-prompt
            active-text="启用"
            inactive-text="停用"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="拉取数据结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetime"
            :default-time="new Date(2000, 1, 1, 23, 59, 59)"
            placeholder="拉取数据结束时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AdvertiserReferralRelation" lang="ts">
import {
  listAdvertiserReferralRelation,
  getAdvertiserReferralRelation,
  delAdvertiserReferralRelation,
  addAdvertiserReferralRelation,
  updateAdvertiserReferralRelation
} from '@/api/oce/advertiserReferralRelation';
import {
  AdvertiserReferralRelationVO,
  AdvertiserReferralRelationQuery,
  AdvertiserReferralRelationForm
} from '@/api/oce/advertiserReferralRelation/types';
import { getListLinkType, getListAppType, advertiserReferralRelation } from '@/api/stock';
import router from '@/router';
import useAppStore from '@/store/modules/app';

import useUserStore from '@/store/modules/user';
const userStore = useUserStore();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const advertiserReferralRelationList = ref<AdvertiserReferralRelationVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const advertiserReferralRelationFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AdvertiserReferralRelationForm = {
  advertiserReferralId: 0,
  thirdAdvertiserId: undefined,
  thirdAdvertiserName: undefined,
  thirdAdvertiserAppCode: undefined,
  referralLinkId: undefined,
  referralLinkType: undefined,
  appType: undefined,
  pullStatus: 1,
  dramaTitle: undefined,
  createName: undefined,
  endTime: undefined,
  startTime: undefined,
  deptId: undefined
};
const data = reactive<PageData<AdvertiserReferralRelationForm, AdvertiserReferralRelationQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    thirdAdvertiserId: undefined,
    thirdAdvertiserName: undefined,
    thirdAdvertiserAppCode: undefined,
    referralLinkId: undefined,
    referralLinkType: undefined,
    appType: undefined,
    pullStatus: undefined,
    dramaTitle: undefined,
    createName: undefined,
    endTime: undefined,
    deptId: undefined,
    orderByColumn: undefined,
    isAsc: undefined,
    params: {}
  },
  rules: {
    thirdAdvertiserName: [{ required: true, message: '广告主账号不能为空', trigger: 'blur' }],
    thirdAdvertiserId: [{ required: true, message: '第三方广告主id不能为空', trigger: 'blur' }],
    createName: [{ required: true, message: '投手名称不能为空', trigger: 'blur' }],
    referralLinkId: [{ required: true, message: '推广链接id不能为空', trigger: 'blur' }],
    referralLinkType: [{ required: true, message: '推广链接类型不能为空', trigger: 'change' }],
    appType: [{ required: true, message: '应用类型能为空', trigger: 'change' }],
    pullStatus: [{ required: true, message: '拉取启用状态：0-停用；1-启用；不能为空', trigger: 'change' }],
    endTime: [{ required: false, message: '拉取数据结束时间', trigger: 'change' }],
    dramaTitle: [{ required: true, message: '短剧名称不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const sum = ref([]);

/** 查询推广链接-广告主关联列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAdvertiserReferralRelation(queryParams.value);
  advertiserReferralRelationList.value = res.rows;
  sum.value = res.sum || [];
  total.value = res.total;
  loading.value = false;
};

const appTypeList = ref([]);
const linkTypeList = ref([]);
/** 类型列表 */
const getAxios = async () => {
  getListLinkType().then((res) => {
    appTypeList.value = res.data;
  });
  getListAppType().then((res) => {
    linkTypeList.value = res.data;
  });
};
const relationList = ref([]);
const formLoading = ref(false);
const remotePerformer = async (query) => {
  form.value.thirdAdvertiserId = '';
  relationList.value = [];
  if (!query) return;
  formLoading.value = true;
  try {
    let res = await advertiserReferralRelation(query);
    relationList.value[0] = res.data;
    form.value.thirdAdvertiserId = res.data.thirdAdvertiserId;
    form.value.thirdAdvertiserAppCode = res.data.appCode;
  } finally {
    formLoading.value = false;
  }
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  advertiserReferralRelationFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdvertiserReferralRelationVO[]) => {
  ids.value = selection.map((item) => item.advertiserReferralId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const sortChangeHandel = ({ order, prop }) => {
  queryParams.value.orderByColumn = prop;
  queryParams.value.isAsc = order === 'ascending' ? 'asc' : 'desc';
  getList();
};

/** 是否启用 */
const handleSetStateSingle = async (item: any) => {
  item._statusLoading = true;
  try {
    await proxy?.$modal.confirm(`是否${item.pullStatus ? '启用' : '停用'}？`);
    await updateAdvertiserReferralRelation(item);
  } catch (error) {
    item.pullStatus = item.pullStatus ? 0 : 1;
  } finally {
    item._statusLoading = false;
  }
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加巨量绑定数据';
};

const clickHandle = (row) => {
  //router.push(`/advertiserEverydayCost?referralLinkId=${row.referralLinkId}`);
  router.push(`/${row.referralLinkType > 3 ? 'advertiserEverydayCostIaa' : 'advertiserEverydayCost'}?referralLinkId=${row.referralLinkId}`);
};

/** 修改按钮操作 */
const handleUpdate = async (row?: AdvertiserReferralRelationVO) => {
  reset();
  const _advertiserReferralId = row?.advertiserReferralId || ids.value[0];
  const res = await getAdvertiserReferralRelation(_advertiserReferralId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改巨量绑定数据';
};

/** 提交按钮 */
const submitForm = () => {
  console.log('form.endTime', form.value.endTime);
  advertiserReferralRelationFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.advertiserReferralId) {
        await updateAdvertiserReferralRelation(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addAdvertiserReferralRelation(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

const computeHeight = () => {
  let baseHeight = 900;
  let totalHeight = document.body.clientHeight;
  if (useAppStore().windowWidth > 500) {
    //计算表格的 高度
    return totalHeight - 450;
  } else {
    return baseHeight;
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: AdvertiserReferralRelationVO) => {
  const _advertiserReferralIds = row?.advertiserReferralId || ids.value;
  await proxy?.$modal
    .confirm('是否确认删除推广链接-广告主关联编号为"' + _advertiserReferralIds + '"的数据项？')
    .finally(() => (loading.value = false));
  await delAdvertiserReferralRelation(_advertiserReferralIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oce/advertiserReferralRelation/export',
    {
      ...queryParams.value
    },
    `advertiserReferralRelation_${new Date().getTime()}.xlsx`
  );
};

const computePermission = computed(() => {
  // 查看用户是否有查询部门权限
  let permissions = userStore.permissions;
  if (permissions.indexOf('oce:advertiserReferralRelation:stop') != -1 || permissions.indexOf('*:*:*') != -1) {
    return false;
  }

  return true;
});

onMounted(() => {
  getList();
  getAxios();
});
</script>
